package cn.monkey.family.server.domain;

import cn.monkey.family.data.UserSelector;
import cn.monkey.family.server.domain.uc.user.UserRepository;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserSelectorConfiguration {

    final CacheManager cacheManager;

    final UserRepository userRepository;

    public UserSelectorConfiguration(CacheManager cacheManager, UserRepository userRepository) {
        this.cacheManager = cacheManager;
        this.userRepository = userRepository;
    }

    @Bean
    public UserSelector userSelector() {
        Cache cache = cacheManager.getCache(UserSelector.KEY);
        return id -> cache == null ? userRepository.findById(id) : cache.get(id, () -> userRepository.findById(id));
    }
}
